package com.itheima.server.service;

import cn.hutool.core.collection.CollUtil;
import com.itheima.api.CommentsApi;
import com.itheima.api.UserInfoApi;
import com.itheima.domain.Comment;
import com.itheima.domain.UserInfo;
import com.itheima.enums.CommentType;
import com.itheima.server.interceptor.UserHolder;
import com.itheima.vo.CommentVo;
import com.itheima.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentsService {

    @DubboReference
    private CommentsApi commentsApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 获取评论列表
     * @param movementId
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult comments(String movementId, Integer page, Integer pagesize) {
        //查询评论去
        PageResult pageResult = commentsApi.comments(movementId,page,pagesize,CommentType.COMMENT );
        List<Comment> items = (List<Comment>) pageResult.getItems();
        if (CollUtil.isEmpty(items)){
            return new PageResult();
        }
        List<Long> userIds = items.stream().map(Comment::getUserId).collect(Collectors.toList());
        //去查userInfo
        Map<Long, UserInfo> userInfos = userInfoApi.getByIds(userIds, null);
        //封装数据
        List<CommentVo> list = new ArrayList<>();
        for (Comment item : items) {
            UserInfo userInfo = userInfos.get(item.getUserId());
            if (userInfo != null){
                CommentVo vo = CommentVo.init(userInfo, item);
                list.add(vo);
            }
        }
        pageResult.setItems(list);
        return pageResult;
    }

    /**
     * 发布评论
     * @param movementId
     * @param comment
     */
    public void publishComments(String movementId, String comment) {
        Long userId = UserHolder.getUserId();
        //封装评论对象
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(userId);
        comment1.setCreated(System.currentTimeMillis());
        //保存去
        commentsApi.publishComments(comment1);
    }


}
